Skip to content

fix(Migrator): disable foreign keys during DropColumn#229

Merged
jinzhu merged 1 commit into
go-gorm:masterfrom
lihan3238:fix-119-dropcolumn-fk
Jun 25, 2026
Merged

fix(Migrator): disable foreign keys during DropColumn#229
jinzhu merged 1 commit into
go-gorm:masterfrom
lihan3238:fix-119-dropcolumn-fk

Conversation

@lihan3238

Copy link
Copy Markdown
Contributor

Closes #119

Problem

DropColumn fails when foreign keys are enabled because it calls recreateTable, which performs DROP TABLE + INSERT INTO + ALTER TABLE RENAME. SQLite enforces FK constraints on the INSERT INTO step, causing the operation to fail with constraint violation errors.

Solution

Wrap DropColumn in RunWithoutForeignKey, following the exact same pattern already used by AlterColumn and DropTable in this file.

Before

func (m Migrator) DropColumn(value interface{}, name string) error {
    return m.recreateTable(value, nil, func(...) { ... })
}

After

func (m Migrator) DropColumn(value interface{}, name string) error {
    return m.RunWithoutForeignKey(func() error {
        return m.recreateTable(value, nil, func(...) { ... })
    })
}

DropColumn calls recreateTable which performs DROP TABLE + INSERT INTO +
ALTER TABLE RENAME. When foreign keys are enabled, SQLite enforces FK
constraints on the INSERT INTO step, causing the operation to fail.

Wrap DropColumn in RunWithoutForeignKey, following the same pattern
already used by AlterColumn and DropTable.

Closes #119
@jinzhu jinzhu merged commit 7230345 into go-gorm:master Jun 25, 2026
3 checks passed
h2zi added a commit to libtnb/sqlite that referenced this pull request Jul 7, 2026
- AlterColumn/DropColumn: accept a table-name string without panicking
  (stmt.Schema is nil then, as in other GORM dialects)
- disable foreign keys during DropColumn/CreateConstraint/DropConstraint
  table rebuilds (go-gorm/sqlite#229) and pin the PRAGMAs plus the
  rebuild transaction to a single pool connection
- recreateTable: recreate indexes and triggers dropped with the old
  table, and rename via legacy_alter_table so tables referenced by
  views can be rebuilt (go-gorm/sqlite#225)
- HasColumn: exact match via pragma_table_info instead of LIKE substring
  matching over the DDL, which had false positives
- HasConstraint: exact constraint-name match via DDL parsing
- GetTables: exclude sqlite_* internal tables
- ColumnTypes: don't let rows.Close() overwrite an earlier error
- getRawDDL: report "table not found" instead of "invalid DDL"
- DropColumn: fail when the column isn't present in the DDL

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

drop column fails when foreign keys are enabled

2 participants